package cn.tsa.share.jdbc.shardingjdbc.db;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * 精确分片
 *
 * @author hongwei
 */
@Slf4j
public class DbPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> preciseShardingValue) {
        Long idValue = preciseShardingValue.getValue();
        long delivery = idValue % 3;
        for (String availableTargetName : availableTargetNames) {
            if (availableTargetName.endsWith(delivery + "")) {
                return availableTargetName;
            }
        }
        log.error("invalid values in shardingResults:{}", idValue);
        throw new IllegalArgumentException("invalid value in hintShardingValue!");
    }
}
